package com.yvon.maple.service.auth.service.impl;

import com.yvon.boot.common.result.GlobalException;
import com.yvon.boot.common.result.ResultCode;
import com.yvon.maple.service.auth.model.LdapUser;
import com.yvon.maple.service.auth.properties.LdapAttribute;
import com.yvon.maple.service.auth.properties.LdapDataProperties;
import com.yvon.maple.service.auth.service.LdapService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.ldap.core.DirContextAdapter;
import org.springframework.ldap.core.LdapTemplate;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.stereotype.Service;

/**
 * ldap service实现类
 *
 * @author : Yvon
 * @since : 2022-02-25
 */
@Service
@Slf4j
public class LdapServiceImpl implements LdapService {

    @Autowired
    private LdapTemplate ldapTemplate;

    @Autowired
    private LdapDataProperties ldapDataProperties;

    @Override
    public LdapUser getUserByUsername(String username) {
        //查询用户信息
        LdapAttribute attributes = ldapDataProperties.attributes;
        String filter = "(&("+ldapDataProperties.getSearchFilter() +")("+attributes.getUsername()+"=" + username + "))";
        try {
            return ldapTemplate.searchForObject("", filter, ctx -> {
                DirContextAdapter context = (DirContextAdapter)ctx;
                LdapUser p = new LdapUser();
                p.setUsername(context.getStringAttribute(attributes.getUsername()));
                p.setName(context.getStringAttribute(attributes.getName()));
                p.setMobile(context.getStringAttribute(attributes.getMobile()));
                p.setEmail(context.getStringAttribute(attributes.getEmail()));
                p.setEmail(context.getStringAttribute(attributes.getEmail()));
                return p;
            });
        }catch (EmptyResultDataAccessException e) {
            throw new GlobalException(ResultCode.LDAP_USER_NOT_FOUND);
        }

    }

    @Override
    public void authentication(String username, String password) {
           LdapAttribute attributes = ldapDataProperties.attributes;
           String filter = "(&("+ldapDataProperties.getSearchFilter() +")("+attributes.getUsername()+"=" + username + "))";
           //使用用户名、密码验证域用户
           boolean result = ldapTemplate.authenticate("", filter, password);
           if (!result) {
               log.error("ldap验证账号和密码错误");
               throw new BadCredentialsException("账户名或者密码输入错误");
           }
    }
}
